/*
 * This file is part of TradeHelper library.
 *
 * TradeHelper library is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * TradeHelper library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with TradeHelper library.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.rag.forum.pages;

import com.alee.utils.swing.AncestorAdapter;
import com.alee.utils.swing.Timer;

import javax.swing.*;
import javax.swing.event.AncestorEvent;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * User: mgarin Date: 07.08.12 Time: 15:04
 */

public class WheelImage extends JComponent
{
    private ImageIcon wheel = new ImageIcon ( WheelImage.class.getResource ( "icons/wheel.png" ) );

    private Timer timer;
    private int angle = 0;

    public WheelImage ()
    {
        super ();
        setOpaque ( false );

        timer = new Timer ( 1000 / 24, new ActionListener ()
        {
            public void actionPerformed ( ActionEvent e )
            {
                angle += 1;
                repaint ();
            }
        } );

        addAncestorListener ( new AncestorAdapter ()
        {
            public void ancestorAdded ( AncestorEvent event )
            {
                timer.start ();
            }

            public void ancestorRemoved ( AncestorEvent event )
            {
                timer.stop ();
            }
        } );
    }

    protected void paintComponent ( Graphics g )
    {
        super.paintComponent ( g );

        Graphics2D g2d = ( Graphics2D ) g;
        g2d.setRenderingHint ( RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR );

        g2d.translate ( wheel.getIconWidth () / 2, wheel.getIconHeight () / 2 );
        if ( angle != 0 )
        {
            g2d.rotate ( angle * Math.PI / 180 );
        }
        g2d.drawImage ( wheel.getImage (), -wheel.getIconWidth () / 2, -wheel.getIconHeight () / 2,
                wheel.getImageObserver () );
    }

    public Dimension getPreferredSize ()
    {
        return new Dimension ( wheel.getIconWidth (), wheel.getIconHeight () );
    }
}